package controllers;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import parts.APart;
import parts.CompositePart;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;

public class PartManagementController {
	String partFilename;
	CompositePart part;
	
	private static PartManagementController instance = null;
	
	public static PartManagementController getInstance() {
		if (instance == null) {
			instance = new PartManagementController();
		}
		
		return instance;
	}
	
	private PartManagementController() {
		partFilename = null;
		part = null;
	}
	
	public CompositePart getPart() {
		return part;
	}
	
	public boolean openPartFile(String filename) {
		if (filename == null || filename.isEmpty()) {
			System.out.println("Invalid filename specified");
			return false;
		}
		try {
			FileReader reader = new FileReader(filename);
			partFilename = filename;
			Gson gson = new Gson();
			part = gson.fromJson(reader, CompositePart.class);
			return true;
		} catch (FileNotFoundException e) {
			System.err.println("The file " + filename + " could not be opened: " + e.getMessage());
			return false;
		} catch (JsonSyntaxException e) {
			System.err.println("Incompatible part file " + filename + ": " + e.getMessage());
			return false;
		} catch (JsonIOException e) {
			System.err.println("Problem opening file: " + filename + ": " + e.getMessage());
			return false;
		}
	}
	
	public boolean savePartFileAs(String filename) {
		if (part == null) {
			System.out.println("Problem with part to be saved");
			return false;
		}
		if (filename == null || filename.isEmpty()) {
			System.out.println("Invalid filename specified");
			return false;
		}
		partFilename = filename;
		Gson gson = new Gson();
		String partAsJson = gson.toJson(part);
		try {
			FileWriter writer = new FileWriter(filename);
			writer.write(partAsJson);
			return true;
		} catch (IOException e) {
			System.out.println("The file " + filename + " could not be opened: " + e.getMessage());
			return false;
		}
	}
	
	public void savePartFile() {
		savePartFileAs(partFilename);
	}
	
	public void closePartFile(APart part) {
		partFilename = null; 
	}
}
